﻿var projectPath = $.getenv("ANDROIDPROJECT");
var originalUnits = preferences.rulerUnits;
// Set unit type to Pixels
preferences.rulerUnits = Units.PIXELS;

//convert backslashes to forward slashes so we don't have any escape issues later

var gotPath = true;
if (projectPath === null)
{
	alert("This script needs an ANDROIDPROJECT environment variable to be set \
	     with the path to your android project");
	gotPath = false;
}

projectPath = projectPath.replace(/\\/g, '/');

// Check if there is an active document
var gotDoc = true;
try{
	// Try to get a reference to an active document
	var docRef = app.activeDocument;
}
catch(e)
{
	alert("You need to have a document open to run this script");
	gotDoc = false;
}

main();
preferences.rulerUnits = originalUnits;

function main()
{
	if (!gotDoc || !gotDoc)
		return;

     var savePath = projectPath + "/images/";
     var saveName = docRef.name.replace(".psd","");
     var saveFile = new File(savePath + saveName + ".png");
	var batchFile = new File(savePath + saveName + ".bat");
	
	var pngOptions = new PNGSaveOptions();
	
	pngOptions.interlace = false;
	pngOptions.transparency = true;

	docRef.saveAs(saveFile, pngOptions, true, Extension.LOWERCASE);
	
	batchFile.open('w');
	
	batchFile.writeln("@echo off");
	batchFile.writeln("echo Performing hqx 2 and adding to drawable-ldpi");
	batchFile.writeln("hqx -s 2 " + savePath + saveName + ".png" + " " + 
							projectPath + "/res/drawable-ldpi/" + saveName + ".png || PAUSE");
	batchFile.writeln("echo Navigating to the drawable-ldpi directory");
	batchFile.writeln("cd /");
	batchFile.writeln("cd " + projectPath.replace("C:/", "") + "/res/drawable-ldpi");
	batchFile.writeln("echo Reducing image back to its original size");
	batchFile.writeln("mogrify -resize " + docRef.width.value + "x" + docRef.height.value + " " + saveName + ".png || PAUSE");
	batchFile.writeln("echo Performing hqx 2 and adding to drawable-mdpi");
	batchFile.writeln("hqx -s 2 " + savePath + saveName + ".png" + " " + 
							projectPath + "/res/drawable-mdpi/" + saveName + ".png || PAUSE");
	batchFile.writeln("echo Performing hqx 3 and adding to drawable-hdpi");
	batchFile.writeln("hqx -s 3 " + savePath + saveName + ".png" + " " + 
							projectPath + "/res/drawable-hdpi/" + saveName + ".png || PAUSE");	
	batchFile.writeln("echo Performing hqx 4 and adding to drawable-xhdpi");
	batchFile.writeln("hqx -s 4 " + savePath + saveName + ".png" + " " + 
							projectPath + "/res/drawable-xhdpi/" + saveName + ".png || PAUSE");						
	batchFile.close();
	
	batchFile.execute();
	
}